import { defineStore } from "pinia";
import {
  type userType,
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import {
  type LoginResult,
  type RefreshTokenResult,
  type LogoutResult,
  loginApi,
  logoutApi,
  getUserInfoApi,
  checkLoginApi,
  refreshTokenApi
} from "@/api/user";
import { useMultiTagsStoreHook } from "./multiTags";
import { usePermissionStoreHook } from "./permission";
import { type DataInfo, setToken, removeToken, userKey } from "@/utils/auth";

export const useUserStore = defineStore("pure-user", {
  state: (): userType => ({
    // 头像
    avatar: storageLocal().getItem<DataInfo<number>>(userKey)?.avatar ?? "",
    // 用户名
    username: storageLocal().getItem<DataInfo<number>>(userKey)?.username ?? "",
    // 昵称
    nickname: storageLocal().getItem<DataInfo<number>>(userKey)?.nickname ?? "",
    // 页面级别权限
    roles: storageLocal().getItem<DataInfo<number>>(userKey)?.roles ?? [],
    // 按钮级别权限
    permissions:
      storageLocal().getItem<DataInfo<number>>(userKey)?.permissions ?? [],
    // 是否勾选了登录页的免登录
    isRemembered: false,
    // 登录页的免登录存储几天，默认7天
    loginDay: 7
  }),
  actions: {
    /** 存储头像 */
    SET_AVATAR(avatar: string) {
      this.avatar = avatar;
    },
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储昵称 */
    SET_NICKNAME(nickname: string) {
      this.nickname = nickname;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 存储按钮级别权限 */
    SET_PERMS(permissions: Array<string>) {
      this.permissions = permissions;
    },
    /** 存储是否勾选了登录页的免登录 */
    SET_ISREMEMBERED(bool: boolean) {
      this.isRemembered = bool;
    },
    /** 设置登录页的免登录存储几天 */
    SET_LOGINDAY(value: number) {
      this.loginDay = Number(value);
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<LoginResult>((resolve, reject) => {
        loginApi(data)
          .then(response => {
            if (response?.code === 200 && response.data) {
              // 转换数据格式以兼容现有的token存储逻辑，包含用户信息
              const tokenData = {
                token: response.data.token,
                accessToken: response.data.token, // 兼容性
                refreshToken: response.data.token, // 使用同一个token
                expires: new Date(Date.now() + response.data.expireTime * 1000),
                // 添加用户信息，让setToken函数能正确保存到localStorage
                username: response.data.userName,
                roles: response.data.roles || [],
                permissions: response.data.permissions || [],
                avatar: response.data.avatar || "", // 使用后端返回的头像
                nickname: response.data.nickname || response.data.userName // 使用后端返回的昵称，默认为用户名
              };
              setToken(tokenData);

              // 更新用户信息到store
              this.SET_USERNAME(response.data.userName);
              this.SET_NICKNAME(
                response.data.nickname || response.data.userName
              );
              this.SET_AVATAR(response.data.avatar || "");
              this.SET_ROLES(response.data.roles || []); // 确保roles不为undefined
              this.SET_PERMS(response.data.permissions || []); // 确保permissions不为undefined

              console.log("登录成功，用户信息:", {
                username: response.data.userName,
                roles: response.data.roles,
                permissions: response.data.permissions
              });

              // 验证localStorage中的数据
              const savedUserData =
                storageLocal().getItem<DataInfo<number>>(userKey);
              console.log("保存到localStorage的用户数据:", savedUserData);

              // 静态路由模式：登录后初始化菜单权限
              usePermissionStoreHook().handleWholeMenus([]);
            }
            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      this.permissions = [];
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();

      // 触发全局登出事件，通知其他组件（如WebSocket服务）
      window.dispatchEvent(new CustomEvent("user-logout"));

      router.push("/login");
    },
    /** 调用后端注销接口 */
    async logout() {
      return new Promise<LogoutResult>((resolve, reject) => {
        logoutApi()
          .then(response => {
            if (response?.code === 200) {
              // 清除本地状态
              this.logOut();
            }
            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 获取用户信息 */
    async getUserInfo() {
      return new Promise<LoginResult>((resolve, reject) => {
        getUserInfoApi()
          .then(response => {
            if (response?.code === 200 && response.data) {
              this.SET_USERNAME(response.data.userName);
              this.SET_NICKNAME(
                response.data.nickname || response.data.userName
              );
              this.SET_AVATAR(response.data.avatar || "");
              this.SET_ROLES(response.data.roles);
              this.SET_PERMS(response.data.permissions);
            }
            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 检查登录状态 */
    async checkLogin() {
      return checkLoginApi();
    },
    /** 刷新`token` */
    async handRefreshToken() {
      return new Promise<RefreshTokenResult>((resolve, reject) => {
        refreshTokenApi()
          .then(response => {
            if (response?.code === 200 && response.data) {
              // 转换数据格式以兼容现有的token存储逻辑，包含用户信息
              const tokenData = {
                token: response.data.token,
                accessToken: response.data.token, // 兼容性
                refreshToken: response.data.token, // 使用同一个token
                expires: new Date(Date.now() + response.data.expireTime * 1000),
                // 添加用户信息，让setToken函数能正确保存到localStorage
                username: response.data.userName,
                roles: response.data.roles || [],
                permissions: response.data.permissions || [],
                avatar: response.data.avatar || "", // 使用后端返回的头像
                nickname: response.data.nickname || response.data.userName // 使用后端返回的昵称，默认为用户名
              };
              setToken(tokenData);

              // 更新用户信息到store
              this.SET_USERNAME(response.data.userName);
              this.SET_NICKNAME(
                response.data.nickname || response.data.userName
              );
              this.SET_AVATAR(response.data.avatar || "");
              this.SET_ROLES(response.data.roles);
              this.SET_PERMS(response.data.permissions);
            }
            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
